package com.crpc.core.loadBalance;

import com.crpc.core.CrpcBootStrap;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wzy
 * @version 1.0
 * @description:
 * @date 2023/10/1 10:53
 */
public abstract class AbstractLoadBalance implements LoadBalance {
    //一个服务会匹配selector
    private final Map<String, Selector> cache = new ConcurrentHashMap<>(8);

    @Override
    public InetSocketAddress selectServiceAddress(String serviceName) {
        //内部维护一个缓存池
        Selector selectorCache = cache.get(serviceName);
        if (selectorCache != null) {
            return selectorCache.getNext();
        }
        List<InetSocketAddress> inetSocketAddressList = CrpcBootStrap.getInstance().getConfiguration().getRegistryConfig().getRegistry().lookup(serviceName);
        //提供一个算法负责选取一个合适节点
        selectorCache = getSelector(inetSocketAddressList);
        cache.put(serviceName, selectorCache);
        //获取可用节点
        return selectorCache.getNext();
    }

    @Override
    public synchronized void reLoadBalance(String serviceName, List<InetSocketAddress> inetSocketAddressList) {
        //根据新的服务列表生成新的selector
        cache.put(serviceName, getSelector(inetSocketAddressList));
    }

    //子类进行扩展
    //返回一个服务负载均衡算法选择器
    public abstract Selector getSelector(List<InetSocketAddress> inetSocketAddressList);

}
